import 'dart:convert';

import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/screen_control_util.dart';
import 'package:enterprise_v6_app/app/data/api/special_list.dart';
import 'package:enterprise_v6_app/app/data/entities/application/get_risk_analysis_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/process_list_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/ticket_receipt_valid_date_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/working_personnel_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/ticket_plan_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/live/live_player_view.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

class ManagementOperationController extends GetxController {
  /// 作业人员列表
  // 是否显示作业人员列表
  bool isShowWorkingPersonnelList = false;

  // 当前作业人数
  int currentWorkingPersonnel = 0;

  // 作业人
  List<String> workingPersonnel = [];

  // 作业负责人
  List<String> responsiblePersonnel = [];

  // 监护人
  List<String> monitoringPersonnel = [];

  /// 作业人列表
  List<WorkingPersonnelEntity> workingPersonnelList = [];

  /// 风险分析对象
  List<GetRiskAnalysisEntity> getRiskAnalysisList = [];

  TicketPlanReceiptLists ticketPlanReceiptLists = Get.arguments as TicketPlanReceiptLists;

  // 倒计时
  TicketReceiptValidDateEntity ticketReceiptValidDateEntity = TicketReceiptValidDateEntity();

  /// webview请求地址
  URLRequest url = URLRequest(url: Uri.parse('${Interface.mapUrl}/#/nest?func=3dDisplay&noScale=true'));

  late InAppWebViewController inAppWebViewController;

  /// 初始化
  _init() async {
    _getTicketReceiptValidDate(true);
    // _checkLayerList();
    _getRiskAnalysisObject();
  }

  /// webview加载完成后
  onWebViewCreated(InAppWebViewController controller) async {
    inAppWebViewController = controller;
    // 如果是debug模式就不加载_loadTile,提高性能
    if (!kDebugMode) {
      // 先加载地形
      await _loadTerrain(Interface.terrainUrl);
      // 加载瓦片
      _loadTileset(Interface.tilesetUrl);
    }
  }

  _loadTerrain(String url) async {
    final data = {
      'type': 'Terrain',
      'data': {
        'url': url,
      }
    };
    await Future.delayed(const Duration(seconds: 3));
    _sendMessage(data);
  }

  /// 加载瓦片地址
  /// [tileUrl] 暂时写死，后面要动态获取
  _loadTileset(String tileUrl) async {
    final data = {
      'type': 'Tileset',
      'data': {
        'url': tileUrl,
      }
    };
    await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  /// 选中的右侧选项
  int? selectedRightIndex;

  // 右侧按钮
  List<GetRiskAnalysisEntity> rightIcon = [];

  // 数据初始化 （第一步操作）
  Future intiData(dynamic list) async {
    final Map<String, dynamic> data = {
      'type': 'DataInit',
      'data': {'group': 'default', 'data': list}
    };
    await _sendMessage(data);
  }

  // 数据显示 之 数据显示  （在第一步之后执行）
  Future<void> dataShow(dynamic list) async {
    final data = {'type': 'DataDisplay', 'data': list};
    _sendMessage(data);
  }

  // 数据显示 之 数据定位  （在第一步之后执行即可）
  Future dataLocation(dynamic map) async {
    final data = {'type': 'DataFlyTo', 'data': map};
    _sendMessage(data);
  }

  // 数据隐藏 （在数据显示之后调用）
  void dataHide() {
    final data = {
      'type': 'DataFlyTo',
      'data': {
        'group': 'default',
        'show': false,
      }
    };
    _sendMessage(data);
  }

  // 数据移除  （在第一步之后执行即可）
  void dataRemove() {
    final data = {
      'type': 'DataRemove',
      'data': {
        'group': 'default',
        'key': '202305151002', // 指定key必须指定group
        'all': true // 第一优先，传了这个为true，则其他两个设置直接无效了
      }
    };
    _sendMessage(data);
  }

  /// 发送消息
  Future<void> _sendMessage(data) async {
    await inAppWebViewController.postWebMessage(message: WebMessage(data: jsonEncode(data)));
  }

  // 点击右侧选项
  void clickRightIcon(int index, GetRiskAnalysisEntity bean) {
    selectedRightIndex = index;
    update();
    clickRightEvent(index, bean);
  }

  // 点击右侧事件
  void clickRightEvent(int index, GetRiskAnalysisEntity bean) {
    if (bean.name == '作业人员') {
      clickWebPerson(index);
    } else {
      clickDynamicButton(index, bean);
    }
  }

  // 点击右侧按钮
  void clickDynamicButton(int index, GetRiskAnalysisEntity bean) async {
    if (bean.jsonDate != null) {
      final data = jsonDecode(bean.jsonDate!);
      // 如果 mode = Pin 则 UIMode = 'PinCommon';
      if (data['mode'] != null && data['mode'] == 'Pin') {
        data['UIMode'] = 'PinCommon';
      }
      await intiData([data]);
      await dataShow(data);
      await dataLocation({
        'key': data['id'] // 必填 （数据DataInit中的id值）
      });
    }
  }

  // 作业人员
  void clickWebPerson(int index) {
    if (!isShowWorkingPersonnelList) {
      _getJobIngList();
    } else {
      isShowWorkingPersonnelList = false;
      selectedRightIndex = null;
      update();
    }
  }

  // 作业中断
  void jobBreak() {
    setPortrait();
    Get.toNamed(
      AppRoutes.workInterruption,
      arguments: {
        'type': 1,
        'value': ticketPlanReceiptLists,
      },
    )?.then((result) {
      if (Get.currentRoute == AppRoutes.manageJobs) {
        setLandscape();
      }
    });
  }

  // 终止作业
  void jobStop() {
    setPortrait();
    Get.toNamed(AppRoutes.workInterruption, arguments: {
      'type': 2,
      'value': ticketPlanReceiptLists,
    })?.then((result) {
      if (Get.currentRoute == AppRoutes.manageJobs) {
        setLandscape();
      }
    });
  }

  // 进入作业票页面
  // [type] 作业状态 0：待开票 1：开票中 2：进行中 3：中断 4：已验收
  // [ticketBigTypeName] 	作业大类字典名称
  Future<void> toJobTicket(TicketPlanReceiptLists bean) async {
    //根据流程唯一编码查询流程详情
    final res = await HttpUtil().generateGetRequest<ProcessListEntity>(Interface.getProcessRecordByProcessEncoding,
        queryParameters: {'processEncoding': bean.processEncoding}).execute();

    res.onSuccess((result) {
      if (result.data != null) {
        final ProcessListEntity entity = result.data!;
        //跳转到作业总页面
        setPortrait();
        Get.toNamed(AppRoutes.workAll, arguments: {
          'ticketBean': bean,
          'businessType': entity.businessType,
        })?.then((value) {
          if (Get.currentRoute == AppRoutes.manageJobs) {
            setLandscape();
          }
          if (value != null) {
            Get.back();
          }
        });
      } else {
        AppToast.showError('获取作业票流程信息失败');
      }
    });
  }

  // 作业验收
  void jobAccept() {
    toJobTicket(ticketPlanReceiptLists);
  }

  // 获取正在作业列表
  void _getJobIngList() async {
    final res = await HttpUtil().generateGetRequest<List<WorkingPersonnelEntity>>(Interface.getWorkPersonnel, queryParameters: {
      'pageNum': 1,
      'pageSize': 10000,
    }).execute();

    res.onSuccess((result) {
      if (result.data != null) {
        workingPersonnelList = result.data!;
        currentWorkingPersonnel = workingPersonnelList.length;
        currentWorkingPersonnel = workingPersonnelList.length;

        /// [operatorType] 0:作业人, 1: 作业负责人 2:监护人
        for (var element in workingPersonnelList) {
          if (element.operatorUserName != null) {
            switch (element.operatorType) {
              case 0:
                workingPersonnel.add(element.operatorUserName!);
                break;
              case 1:
                responsiblePersonnel.add(element.operatorUserName!);
                break;
              case 2:
                monitoringPersonnel.add(element.operatorUserName!);
                break;
              default:
                break;
            }
          }
        }
        isShowWorkingPersonnelList = true;
        update();
      }
    });
  }

  // 会议按钮
  void mettingButton() {}

  // 交接班
  reliefOfAShift() {
    setPortrait();
    Get.toNamed(
      AppRoutes.changeShiftsPage,
      arguments: ticketPlanReceiptLists,
    )?.then((result) {
      setLandscape();
    });
  }

  // 违规登记
  illegalRegistration() {
    setPortrait();
    Get.toNamed(
      AppRoutes.violationRecordsPage,
      arguments: ticketPlanReceiptLists,
    )?.then((result) {
      setLandscape();
    });
  }

  //  进入直播界面
  liveVideoRecording() async {
    setPortrait();
    Get.toNamed(AppRoutes.livePush, arguments: ticketPlanReceiptLists)?.then((value) {
      setLandscape();
    });
  }

  // 直播录像
  void toLiveView() {
    setPortrait();
    Get.to(LivePlayer.new, arguments: ticketPlanReceiptLists)?.then((value) {
      setLandscape();
    });
  }

  ///获取数据气体检测有效期
  _getTicketReceiptValidDate(bool isShowTimer) async {
    //如果要显示才去请求
    if (isShowTimer) {
      final res = await SpecialListApis.getListConfigByTicketReceiptId(ticketPlanReceiptLists.id ?? '').execute();
      res.onSuccess((result) {
        if (result.data != null && result.data!.gasDetectionValidDate != 0) {
          ticketReceiptValidDateEntity = result.data!;
          update();
        }
      });
    }
  }

  /// 获取所有风险分析对象（一般危险源)
  _getRiskAnalysisObject() async {
    final res = await SpecialListApis.getRiskAnalysisObject().execute();
    res.onSuccess((result) {
      if (result.data != null && result.data!.isNotEmpty) {
        getRiskAnalysisList = result.data!;
        for (var i in getRiskAnalysisList) {
          rightIcon.add(i);
        }
        rightIcon.add(GetRiskAnalysisEntity(
          name: '作业人员',
          logoIcon: AppImages.icon_web_person,
          status: 0,
        ));
        update();
      }
    });
  }

  // 返回
  void goBack() {
    Get.back();
  }

  // 更多作业
  void moreWork() {
    setPortrait();
    Get.toNamed(AppRoutes.workingPersonnelList, arguments: workingPersonnelList)?.then((result) {
      setLandscape();
    });
  }

  // 设置影藏状态栏
  void setStatusBarHidden(bool hidden) {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky, overlays: []);
  }

  // 设置横屏
  void setLandscape() {
    ScreenControlUtils.setting();
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky, overlays: []);
  }

  // 设置竖屏
  void setPortrait() {
    ScreenControlUtils.settingPortrait();
    SystemChrome.setEnabledSystemUIMode(
      SystemUiMode.manual,
      overlays: SystemUiOverlay.values,
    );
  }


  @override
  void onInit() {
    super.onInit();
    _init();
    setLandscape();
  }

  @override
  void onClose() {
    super.onClose();
    setPortrait();
  }
}
